package com.school.vaccination.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.school.vaccination.domain.Inventory;
import com.school.vaccination.domain.Vaccine;
import com.school.vaccination.mapper.InventoryMapper;
import com.school.vaccination.mapper.VaccineMapper;
import com.school.vaccination.model.InventoryModel;
import com.school.vaccination.service.InventoryService;
import zhibi.common.support.base.Page;
import zhibi.common.support.base.service.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhibi.common.support.exception.MessageException;
import zhibi.common.support.mybatis.example.Example;

/**
* The class create by 执笔 on generate.
*/
@Service
@Transactional
public class InventoryServiceImpl extends BaseServiceImpl<Inventory> implements InventoryService {

    @Autowired
    public InventoryServiceImpl(InventoryMapper mapper) {
        super(mapper);
        this.inventoryMapper = mapper;
    }
    private InventoryMapper inventoryMapper;

    @Autowired
    private VaccineMapper vaccineMapper;

    @Override
    public PageInfo<InventoryModel> selectModel(Example example, Page page) {
        if(page != null){
            PageHelper.startPage(page.getPageNum(),page.getPageSize());
        }
        return new PageInfo<>(inventoryMapper.selectModel(example),Page.NAV_SIZE);
    }

    @Override
    public void insertInventory(Inventory inventory) {
        Vaccine vaccine = vaccineMapper.selectByPrimaryKey(inventory.getVaccineId());
        if(null == vaccine){
            throw new MessageException("选择的疫苗不存在");
        }
        vaccine.setCount(vaccine.getCount() + inventory.getReceiveCount());
        vaccineMapper.updateByPrimaryKeySelective(vaccine);
        inventoryMapper.insertSelective(inventory);
    }

    @Override
    public void updateInventory(Inventory inventory) {
        Vaccine vaccine = vaccineMapper.selectByPrimaryKey(inventory.getVaccineId());
        if(null == vaccine){
            throw new MessageException("选择的疫苗不存在");
        }
        Inventory inventoryTemp = inventoryMapper.selectByPrimaryKey(inventory.getId());
        vaccine.setCount(vaccine.getCount() + inventory.getReceiveCount() - inventoryTemp.getReceiveCount());
        vaccineMapper.updateByPrimaryKeySelective(vaccine);
        inventoryMapper.updateByPrimaryKeySelective(inventory);
    }
}